const express = require("express");
const expressJoi = require("@escook/express-joi");

const registerRoutes = (router, moduleName) => {
	const { Add, Info, Search, Update } = require(`../../router_handler/superAdmin/${moduleName}`);
	const { add_Schema, update_Schema } = require(`../../schema/superAdmin/${moduleName}`);
	const { IsShow, Delete } = require("../../router_handler/public/default");
	const { search_Schema, isShow_Schema, del_Schema } = require("../../schema/public/default");

	const routes = [
		{ method: "post", path: "/add", schema: add_Schema, handler: Add },
		{ method: "get", path: "/info", schema: null, handler: Info },
		{ method: "get", path: "/search/:value", schema: search_Schema, handler: Search },
		{ method: "put", path: "/update", schema: update_Schema, handler: Update },
		{ method: "put", path: "/isShow", schema: isShow_Schema, handler: IsShow },
		{ method: "delete", path: "/del/:id", schema: del_Schema, handler: Delete }
	];

	routes.forEach(route => {
		const handlerWithTable = (req, res) => route.handler(req, res, moduleName);
		if (route.schema) {
			router[route.method](route.path, expressJoi(route.schema), handlerWithTable);
		} else {
			router[route.method](route.path, handlerWithTable);
		}
	});
};

module.exports = function createModuleRouter(moduleName) {
	const router = express.Router();
	registerRoutes(router, moduleName);
	return router;
};